package com.gm.wholesale.module.good.view;

import android.content.Context;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.gm.commonlib.base.baseBean.BaseListResp;
import com.gm.commonlib.base.baseBean.BasePageData;
import com.gm.commonlib.base.baseui.baseFragment.BaseFragment;
import com.gm.commonlib.filters.RegexConstant;
import com.gm.commonlib.filters.RegexResultFilter;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.util.numberUtils.DigitUtil;
import com.gm.commonlib.util.numberUtils.NumberUtils;
import com.gm.commonlib.views.choiceview.CustomItemChoosenEntity;
import com.gm.commonlib.views.choiceview.CustomItemChosenButton;
import com.gm.commonlib.views.dialog.DialogUtil;
import com.gm.commonlib.views.dialog.InputDialog;
import com.gm.commonlib.views.dialog.loadingDialog.LoadingDialog;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.R;
import com.gm.wholesale.module.good.GoodType;
import com.gm.wholesale.module.good.bean.CreateGoodReq;
import com.gm.wholesale.module.good.bean.GoodBean;
import com.gm.wholesale.module.good.bean.GoodDetailBean;
import com.gm.wholesale.module.good.bean.GoodListBean;
import com.gm.wholesale.module.good.model.GoodModel;
import com.gm.wholesale.module.good.ui.goodManger.CreateGoodFragment;
import com.gm.wholesale.module.kind.bean.KindBean;
import com.gm.wholesale.module.unit.bean.UnitBean;
import com.gm.wholesale.module.unit.model.UnitModel;
import com.gm.wholesale.util.ViewUtil;

import java.util.ArrayList;
import java.util.List;

public class CreateInventoryGoodView extends LinearLayout implements View.OnClickListener {
    private CustomItemChosenButton choiceKindTv;
    private ImageView addKindImg;
    private CustomItemChosenButton choiceUnitTv;
    private EditText prictEd;
    private CustomItemChosenButton choiceUnit1;
    private EditText prict1Ed;
    private CustomItemChosenButton choiceUnit2;
    private EditText prict2Ed;
    private CustomItemChosenButton choiceUnit3;
    private EditText prict3Ed;


    private UnitBean mInventoryUnit;
    private UnitBean mUnit1;
    private UnitBean mUnit2;
    private UnitBean mUnit3;



    private Context mContext;

    private CreateGoodFragment fragment;

    private CreateGoodNtDialogView mDialogView;


    public CreateInventoryGoodView(Context context) {
        super(context);
        initView(context);
    }

    public CreateInventoryGoodView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public void setCreateGoodFragment(CreateGoodFragment fragment) {
        this.fragment = fragment;
    }

    private void initView(Context context) {
        mContext = context;

        LayoutInflater.from(context).inflate(R.layout.view_create_inventory_good, this);
        choiceKindTv = findViewById(R.id.choiceKindTv);
        addKindImg = findViewById(R.id.addKindImg);
        choiceUnitTv = findViewById(R.id.choiceUnitTv);
        prictEd = findViewById(R.id.prictEd);
        choiceUnit1 = findViewById(R.id.choiceUnit1);
        prict1Ed = findViewById(R.id.prict1Ed);
        choiceUnit2 = findViewById(R.id.choiceUnit2);
        prict2Ed = findViewById(R.id.prict2Ed);
        choiceUnit3 = findViewById(R.id.choiceUnit3);
        prict3Ed = findViewById(R.id.prict3Ed);
        choiceKindTv.setOnClickListener(this);
        addKindImg.setOnClickListener(this);
        choiceUnitTv.setOnClickListener(this);
        choiceUnit1.setOnClickListener(this);
        choiceUnit2.setOnClickListener(this);
        choiceUnit3.setOnClickListener(this);
        setInputFilter(prictEd);
        setInputFilter(prict1Ed);
        setInputFilter(prict2Ed);
        setInputFilter(prict3Ed);

        choiceKindTv.setOnCustomItemClickListener(new CustomItemChosenButton.IOnCustomItemClickListener() {
            @Override
            public void onItemChoosenButtonClick(CustomItemChosenButton button, int itemText, CustomItemChoosenEntity entity) {
                fragment.mChoiceKind = (KindBean) entity;
            }
        });
        choiceUnitTv.setOnCustomItemClickListener(new CustomItemChosenButton.IOnCustomItemClickListener() {
            @Override
            public void onItemChoosenButtonClick(CustomItemChosenButton button, int itemText, CustomItemChoosenEntity entity) {
                UnitBean newUnit=   (UnitBean) entity;
                //todo 选择的和前面的单位一样不处理
                if (mInventoryUnit!=null && mInventoryUnit.getId()==newUnit.getId()){
                    return;
                }

                if (mUnit1!=null || mUnit2!=null || mUnit3!=null){
                    if (mDialogView==null){
                        mDialogView=new CreateGoodNtDialogView(getContext());
                    }
                    mDialogView.show(new CreateGoodNtDialogView.OnFunctionListener() {
                        @Override
                        public void onItem1Click() {
                            mInventoryUnit = (UnitBean) entity;
                            updateChoiceUnit();
                        }

                        @Override
                        public void onItem2Click() {
                            mInventoryUnit = (UnitBean) entity;
                            resetChoiceUnit();
                        }

                        @Override
                        public void onItem3Click() {
                            choiceUnitTv.setText(mInventoryUnit.getName());
                        }

                    });
                }
                else {
                    mInventoryUnit = (UnitBean) entity;
                }

            }
        });

        choiceUnit1.setOnCustomItemClickListener(new CustomItemChosenButton.IOnCustomItemClickListener() {
            @Override
            public void onItemChoosenButtonClick(CustomItemChosenButton button, int itemText, CustomItemChoosenEntity entity) {
                mUnit1 = (UnitBean) entity;
                if (mUnit1.getId()<=0){
                    choiceUnit1.setText("");
                    prict1Ed.setText("");
                    mUnit1=null;
                    return;
                }
                showSetUnitProportion(choiceUnit1, mUnit1, mInventoryUnit, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mUnit1 = null;
                    }
                });
            }
        });
        choiceUnit2.setOnCustomItemClickListener(new CustomItemChosenButton.IOnCustomItemClickListener() {
            @Override
            public void onItemChoosenButtonClick(CustomItemChosenButton button, int itemText, CustomItemChoosenEntity entity) {
                mUnit2 = (UnitBean) entity;
                if (mUnit2.getId()<=0){
                    choiceUnit2.setText("");
                    prict2Ed.setText("");
                    mUnit2=null;
                    return;
                }
                showSetUnitProportion(choiceUnit2, mUnit2, mInventoryUnit, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mUnit2 = null;
                    }
                });

            }
        });
        choiceUnit3.setOnCustomItemClickListener(new CustomItemChosenButton.IOnCustomItemClickListener() {
            @Override
            public void onItemChoosenButtonClick(CustomItemChosenButton button, int itemText, CustomItemChoosenEntity entity) {
                mUnit3 = (UnitBean) entity;
                if (mUnit3.getId()<=0){
                    choiceUnit3.setText("");
                    prict3Ed.setText("");
                    mUnit3=null;
                    return;
                }
                showSetUnitProportion(choiceUnit3, mUnit3, mInventoryUnit, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mUnit3 = null;
                    }
                });
            }
        });



    }

    private void showSetUnitProportion(CustomItemChosenButton chosenButton, UnitBean choiceUnit, UnitBean mInventoryUnit, View.OnClickListener cancleListener) {
        InputDialog inputDialog = DialogUtil.showInputDialog(mContext, "设置单位比例", "", new InputDialog.OnSubMitBtnClickListener() {
            @Override
            public void onSubMitBtnClick(String inputData, InputDialog inputDialog) {
                if (TextUtils.isEmpty(inputData)) {
                    ToastUtil.showToast("单位比例不能为空");
                    return;
                }
                choiceUnit.setProportionNum(inputData);
                String text = choiceUnit.getName() + " (1" + choiceUnit.getName() + "=" + inputData + mInventoryUnit.getName()+")";

                SpannableStringBuilder builder = new SpannableStringBuilder(text);
                AbsoluteSizeSpan absoluteSizeSpan = new AbsoluteSizeSpan(20);
                builder.setSpan(absoluteSizeSpan, 0, text.indexOf("("), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                chosenButton.setText(builder);
                inputDialog.dismiss();
            }
        });
        inputDialog.leftTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chosenButton.setText("");
                cancleListener.onClick(v);
                inputDialog.dismiss();

            }
        });
        inputDialog.setEdInputFilter(new InputFilter[]{new RegexResultFilter(RegexConstant.MAX_MONEY_VALUE_92)});
        inputDialog.showTextView("1" + choiceUnit.getName() + "=", mInventoryUnit.getName());
    }

    private void setInputFilter(EditText editText) {
        editText.setFilters(new InputFilter[]{new RegexResultFilter(RegexConstant.MAX_MONEY_VALUE_92)});
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.addKindImg) {
            fragment.createKind(choiceKindTv);
        } else if (id == R.id.choiceKindTv) {
            fragment.showKind(choiceKindTv);
        } else if (id == R.id.choiceUnitTv) {
            choiceUnit(choiceUnitTv, true);
        } else if (id == R.id.choiceUnit1) {
            choiceUnit(choiceUnit1);
        } else if (id == R.id.choiceUnit2) {
            choiceUnit(choiceUnit2);
        } else if (id == R.id.choiceUnit3) {
            choiceUnit(choiceUnit3);
        }
    }

    private void resetChoiceUnit(){
        mUnit1=null;
        choiceUnit1.setText("");
        mUnit2=null;
        choiceUnit2.setText("");
        mUnit3=null;
        choiceUnit3.setText("");
    }

    private void updateChoiceUnit(){
        if (mUnit1!=null){
            String text = mUnit1.getName() + " (1" + mUnit1.getName() + "=" + NumberUtils.subZeroAndDot(mUnit1.getProportionNum()) + mInventoryUnit.getName()+")";
            setUnitText(choiceUnit1,text);
        }
        if (mUnit2!=null){
            String text = mUnit2.getName() + " (1" + mUnit2.getName() + "=" + NumberUtils.subZeroAndDot(mUnit2.getProportionNum()) + mInventoryUnit.getName()+")";
            setUnitText(choiceUnit2,text);
        }
        if (mUnit3!=null){
            String text = mUnit3.getName() + " (1" + mUnit3.getName() + "=" + NumberUtils.subZeroAndDot(mUnit3.getProportionNum()) + mInventoryUnit.getName()+")";
            setUnitText(choiceUnit3,text);
        }

    }

    private void setUnitText(CustomItemChosenButton textView,String text){
        if (textView==null || TextUtils.isEmpty(text)) return;
        SpannableStringBuilder builder = new SpannableStringBuilder(text);
        AbsoluteSizeSpan absoluteSizeSpan = new AbsoluteSizeSpan(20);
        builder.setSpan(absoluteSizeSpan, 0, text.indexOf("("), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        textView.setText(builder);
    }

    private void choiceUnit(CustomItemChosenButton chosenButton) {
        choiceUnit(chosenButton, false);
    }


    private void choiceUnit(CustomItemChosenButton chosenButton, boolean isChoiceInventoryUnit) {
        if (mInventoryUnit == null && !isChoiceInventoryUnit) {
            ToastUtil.showToast("请先选择库存单位");
            return;
        }
        fragment.choiceUnit(chosenButton,isChoiceInventoryUnit);
    }

    public void showView(GoodDetailBean goodBean) {
         if (goodBean.getCategory()!=null){
             choiceKindTv.setText(goodBean.getCategory().getPrimaryName());
         }
        List<GoodListBean.UnitsBean> unitsBeans = goodBean.getUnits();
        if (unitsBeans != null) {
            for (GoodListBean.UnitsBean unitsBean : unitsBeans) {
                //仅库存商品生效，1库存单位，2辅助单位
                if (unitsBean.getType() == 1) {
                    choiceUnitTv.setText(unitsBean.getName());
                    if (!TextUtils.isEmpty(unitsBean.getPrice())) {
                        prictEd.setText(NumberUtils.subZeroAndDot(unitsBean.getPrice()));
                    }
                    mInventoryUnit = new UnitBean();
                    mInventoryUnit.setId(unitsBean.getId());
                    mInventoryUnit.setName(unitsBean.getName());
                    mInventoryUnit.setProportionNum(unitsBean.getRatio());
                    mInventoryUnit.setPrice(unitsBean.getPrice());
                    unitsBeans.remove(unitsBean);
                    break;
                }
            }
        }
        if (!unitsBeans.isEmpty()) {
            int pos = 0;
            for (GoodListBean.UnitsBean unitsBean : unitsBeans) {
                showUnit(pos, unitsBean);
                pos++;
            }
        }


    }

    private void showUnit(int pos, GoodListBean.UnitsBean unitsBean) {
        String unitText = unitsBean.getName() + "(1" + unitsBean.getName() + "=" + NumberUtils.subZeroAndDot(unitsBean.getRatio()) + mInventoryUnit.getName()+")";
        SpannableStringBuilder builder = new SpannableStringBuilder(unitText);
        AbsoluteSizeSpan absoluteSizeSpan = new AbsoluteSizeSpan(20);
        builder.setSpan(absoluteSizeSpan, 0, unitText.indexOf("("), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);


        switch (pos) {
            case 0:
                mUnit1=unitsBean.getUnitBean();
                choiceUnit1.setText(builder);
                if (!TextUtils.isEmpty(unitsBean.getPrice())){
                    prict1Ed.setText(NumberUtils.subZeroAndDot(unitsBean.getPrice()));
                }
                break;
            case 1:
                mUnit2=unitsBean.getUnitBean();
                choiceUnit2.setText(builder);
                if (!TextUtils.isEmpty(unitsBean.getPrice())){
                    prict2Ed.setText(NumberUtils.subZeroAndDot(unitsBean.getPrice()));
                }
                break;
            case 2:
                mUnit3=unitsBean.getUnitBean();
                choiceUnit3.setText(builder);
                if (!TextUtils.isEmpty(unitsBean.getPrice())){
                    prict3Ed.setText(NumberUtils.subZeroAndDot(unitsBean.getPrice()));
                }
                break;

        }
    }
    public  boolean checkData(String goodName){
        if (TextUtils.isEmpty(goodName)){
            ToastUtil.showToast("请输入商品名称");
            return false;
        }
        if (mInventoryUnit==null){
            ToastUtil.showToast("请选择库存单位");
            return false;
        }
        return true;
    }


    public CreateGoodReq getCreateGoodReq(String goodName) {
        CreateGoodReq createGoodReq = new CreateGoodReq();
        if (fragment.mChoiceKind != null) {
            createGoodReq.setCategoryId(fragment.mChoiceKind.getId());
        }
        createGoodReq.setName(goodName);
        //2: 非库存商品，3: 库存商品
        createGoodReq.setType(GoodType.INVENTORY_GOOD);
        List<CreateGoodReq.UnitsBean> unitBeans = new ArrayList<>();


        //todo 库存单位
        CreateGoodReq.UnitsBean unitsBean = new CreateGoodReq.UnitsBean();
        if (mInventoryUnit!=null){
            unitsBean.setId(mInventoryUnit.getId());
        }
        //仅库存商品生效，1库存单位，2辅助单位
        unitsBean.setType(1);
        unitsBean.setRatio("1");
        String price1 = prictEd.getText().toString();
        if (!TextUtils.isEmpty(price1)) {
            unitsBean.setPrice(price1);
        }
        unitBeans.add(unitsBean);


        //todo 辅助单位
        if (getUnitsBean(mUnit1, prict1Ed) != null) {
            unitBeans.add(getUnitsBean(mUnit1, prict1Ed));
        }
        if (getUnitsBean(mUnit2, prict2Ed) != null) {
            unitBeans.add(getUnitsBean(mUnit2, prict2Ed));
        }
        if (getUnitsBean(mUnit3, prict3Ed) != null) {
            unitBeans.add(getUnitsBean(mUnit3, prict3Ed));
        }
        createGoodReq.setUnits(unitBeans);
        return createGoodReq;

    }


    private CreateGoodReq.UnitsBean getUnitsBean(UnitBean data, EditText priceEd) {
        if (data != null) {
            CreateGoodReq.UnitsBean unitsBean = new CreateGoodReq.UnitsBean();
            unitsBean.setId(data.getId());
            unitsBean.setType(2);
            unitsBean.setRatio(data.getProportionNum());
            String price = priceEd.getText().toString();
            if (!TextUtils.isEmpty(price)) {
                unitsBean.setPrice(price);
            }
            return unitsBean;
        }
        return null;
    }
}
